package com.k.kpp.configfile;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author k
 */
public class XmlFileModifyServiceImpl {

    public static void main(String[] args) {
        String pathname = "e:/test/config/log4j2.xml";
        String path = "/ICC/Component/DBConn/dbname";
        path = "/Configuration/Properties/Property[@name='logDir']";

        File src = new File(pathname);
        File srcBack = new File(pathname+".back");

        try {
            FileUtils.copyFile(src,srcBack);
            System.out.println("backup success!");

            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new File(pathname));

            Element e = (Element) document.selectSingleNode(path);
            String txt = e.getText();
            System.out.println("修改前值："+txt);
            e.setText("e:/logs");
            System.out.println("修改后值："+e.getText());

            // 修改后的 document 持久到文件
            Writer writer = new FileWriter(new File("e:/log4j2G1.xml"));
            document.write(writer);
            writer.flush();
//            XMLWriter writer = new XMLWriter(new FileWriterWithEncoding("e:/log4j2G.xml", StandardCharsets.UTF_8));
//            writer.write(document);
//            writer.flush();

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
